package com.md.api.common.utils;


import com.md.api.common.config.RedisKeys;
import com.md.api.entity.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * token相关方法
 *
 * @create 2020-08-26 10:27
 **/
@Slf4j
@Service
public class TokenUtil {



    @Resource
    RedisUtil redisUtil;
    /**
     * 获取请求的token
     */
    public String getUserId(HttpServletRequest httpRequest) {
        //从header中获取token
        String token = httpRequest.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isEmpty(token)) {
            token = httpRequest.getParameter("token");
        }
        UserInfo user = null;
        user = (UserInfo)redisUtil.get(RedisKeys.getUserTokenInfoKey(token));
        if (null!=user){
            return user.getUserId();
        }
        return null;
    }
    public UserInfo getUserInfo(HttpServletRequest httpRequest) {
        //从header中获取token
        String token = httpRequest.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isEmpty(token)) {
            token = httpRequest.getParameter("token");
        }
        UserInfo user = null;
        user = (UserInfo)redisUtil.get(RedisKeys.getUserTokenInfoKey(token));
        if (null!=user){
            return user;
        }
        return null;
    }
}
